package com.ww.gss.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ww.gss.aspect.GSSHttpRequestWrapper;
import com.ww.gss.exceptions.BusinessException;
import com.ww.gss.util.GSSSystemUtils;
import com.ww.gss.util.GSSWebUtil;
import com.ww.gss.util.SystemConstans;
import com.ww.gss.vo.GSSTokenVO;
import com.ww.gss.vo.param.DBOpsParam;

public class UserSecurityFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private TokenService tokenservice;

    public TokenService getTokenservice() {
        return tokenservice;
    }

    public void setTokenservice(TokenService tokenservice) {
        this.tokenservice = tokenservice;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletrequest = (HttpServletRequest) request;
        HttpServletResponse servletresponse = (HttpServletResponse) response;

        String servername = servletrequest.getServerName();
        logger.info("servername ===========>" + servername);
        String reqeusturl = servletrequest.getRequestURL().toString();
        logger.info("reqeust url ===========>" + reqeusturl);

        if (GSSSystemUtils.isInWhiteList(reqeusturl)) {
            logger.info("==========No need Validation================");
            chain.doFilter(request, response);
            return;
        } else {
            GSSHttpRequestWrapper wrapper = new GSSHttpRequestWrapper(servletrequest);
            GSSTokenVO tokenvo = GSSWebUtil.getTokenInRequest(wrapper);
            String inputtoken = tokenvo.getToken();
            if (GSSSystemUtils.isStrNull(inputtoken)) {
                logger.info("==========Null Token================");
                //GSSWebUtil.sendJson4Error(SystemConstans.RESPONSE_LABEL_APPLICATION_ERROR, "invalid token", servletresponse);
                //return;
            } else {
                // validate token

            }
            chain.doFilter(wrapper, response);
        }

        return;

    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}
